<template>
  <component ref="component" :is="componentContent"></component>
</template>

<script>
// 动态组件,根据传入的组件路径进行加载
export default {
  name: 'DynamicComponent',
  props: {
    // 组件路径, 使用优先级:importPath > componentName
    componentName: String,
    importPath: String,
    // 可选, 根据自己的需要自定义组件的方法, 参数等
    componentObj: Object
  },
  data () {
    return {
      componentContent: null,
      component: null
    }
  },
  created () {
    let path = this.importPath
      ? this.importPath
      : './' + this.componentName + '.vue'
    if (!path || path === '') {
      return
    }
    import(`${path}`).then(module => {
      module = module.default
      let name = module.name
      let res = this.componentObj || {}
      // template如果不存在,默认为无参数的标签
      res['template'] = res['template'] || `<${name}></${name}>`
      res['components'] = res['components'] || {}
      // components强制必须存在组件的引用声明
      res.components[name] = module
      this.componentContent = res
    })
  },
  methods: {
    getComponent () {
      return this.$refs['component']
    }
  }
}
</script>

<style></style>
